package com.eqdd.yiqidian.ui.select;

import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;

import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.RecyclerViewFragmentCustom;
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport;
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx;
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector;
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector;
import com.eqdd.yiqidian.base.BaseFragment;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.rebuild.CareerListResultBean;
import com.eqdd.yiqidian.bean.rebuild.DepartmentListResultBean;
import com.eqdd.yiqidian.bean.rebuild.EmploymentListResultBean;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.http.JsonConverter;
import com.eqdd.yiqidian.utils.ListUtil;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okrx2.adapter.FlowableBody;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Flowable;

/**
 * Created by lvzhihao on 17-5-15.
 */

public class SelectPostMultiFragment extends BaseFragment {
    private RecyclerViewFragmentCustom databinding;

    private DepartmentListResultBean departmentListResultBean;

    private SlimAdapterEx slimAdapterEx;
    private DepartmentListResultBean departmentChoose;
    private ArrayList<Object> datas = new ArrayList<>();
    private List<DepartmentListResultBean> departList = new ArrayList<>();
    private List<EmploymentListResultBean> employList = new ArrayList<>();
    private List<CareerListResultBean> careerList;
    private int updateNum;

    @Override
    protected void setView() {
        if (slimAdapterEx == null) {
            databinding.recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

            slimAdapterEx = SlimAdapterEx.create().register(R.layout.item_edit_title_type, new SlimInjector<String>() {
                @Override
                public void onInject(String data, IViewInjector injector) {
                    injector.text(R.id.tv_top_title, data);
                }
            }).register(R.layout.list_item_25, new SlimInjector<CareerListResultBean>() {
                @Override
                public void onInject(CareerListResultBean data, IViewInjector injector) {
                    injector.text(R.id.tv_content, data.getName())
                            .checked(R.id.checkbox, data.isCheck())
                            .text(R.id.tv_right, data.isCheck() ? data.getNum() + "人" : "");
                }
            }).register(R.layout.list_item_section, new SlimInjector<DepartmentListResultBean>() {
                @Override
                public void onInject(DepartmentListResultBean data, IViewInjector injector) {
                    injector.text(R.id.tv_name, data.getDepartName());
                }
            }).register(R.layout.list_item_04, new SlimInjector<EmploymentListResultBean>() {
                @Override
                public void onInject(EmploymentListResultBean data, IViewInjector injector) {
                    injector.text(R.id.tv_content, data.getStaffName())
                            .imageCircle(R.id.iv_head, data.getIphoto())
                            .checked(R.id.checkbox, data.isCheck())
                            .enable(R.id.checkbox, false);
                }
            }).attachTo(databinding.recyclerView);
            ItemClickSupport.addTo(databinding.recyclerView).setOnItemClickListener((rv, p, v) -> {

                if (slimAdapterEx.getData().get(p) instanceof DepartmentListResultBean) {
                    departmentChoose = (DepartmentListResultBean) slimAdapterEx.getData().get(p);
                    ((SelectPostMultiActivity) getActivity()).addFragment(departmentChoose);
                } else if (slimAdapterEx.getData().get(p) instanceof CareerListResultBean) {
                    CareerListResultBean bean = (CareerListResultBean) slimAdapterEx.getDataItem(p);
                    if (bean.isCheck()) {
                        bean.setCheck(false);
                        for (EmploymentListResultBean employmentListResultBean : employList) {
                            if (employmentListResultBean.getPostId() == bean.getId()) {
                                employmentListResultBean.setCheck(false);
                                SelectPostMultiActivity.totalNum--;
                            }
                        }
                        bean.setNum(0);
                        SelectPostMultiActivity.selectedBeans.remove(bean);
                    } else {
                        bean.setCheck(true);
                        int careerNum = 0;
                        for (EmploymentListResultBean employmentListResultBean : employList) {
                            if (employmentListResultBean.getPostId() == bean.getId()) {
                                employmentListResultBean.setCheck(true);
                                SelectPostMultiActivity.totalNum++;
                                careerNum++;
                            }
                        }
                        bean.setNum(careerNum);
                        bean.setDepartName(departmentListResultBean.getDepartName());
                        SelectPostMultiActivity.selectedBeans.add(bean);
                    }
                    slimAdapterEx.notifyItemChanged(p);
                    if (slimAdapterEx.getData().size() - updateNum > 0) {
                        slimAdapterEx.notifyItemRangeChanged(updateNum, slimAdapterEx.getData().size() - updateNum);
                    }
                }
            });
        }
        refresh();
    }

    public void refresh() {
        departList.clear();
        employList.clear();
        Flowable<HttpResult<List<DepartmentListResultBean>>> departFlow = OkGo.<HttpResult<List<DepartmentListResultBean>>>post(HttpConfig.BASE_URL + HttpConfig.Select_SECTION)
                .params("ParentId", departmentListResultBean.getDepartId())
                .params("CompanyId", departmentListResultBean.getCompanyId())
                .converter(new JsonConverter<HttpResult<List<DepartmentListResultBean>>>() {
                    @Override
                    public void test() {
                        super.test();
                    }
                })
                .adapt(new FlowableBody<>());
        Flowable<HttpResult<List<CareerListResultBean>>> careerFlow = OkGo.<HttpResult<List<CareerListResultBean>>>post(HttpConfig.BASE_URL + HttpConfig.SELECT_CAREER)
                .params("companyId", departmentListResultBean.getCompanyId())
                .params("departId", departmentListResultBean.getDepartId())
                .converter(new JsonConverter<HttpResult<List<CareerListResultBean>>>() {
                    @Override
                    public void test() {
                        super.test();
                    }
                })
                .adapt(new FlowableBody<>());
        Flowable<HttpResult<List<EmploymentListResultBean>>> employmentFlow = OkGo.<HttpResult<List<EmploymentListResultBean>>>post(HttpConfig.BASE_URL + HttpConfig.SELECT_EMPLOYMENT)
                .params("departId", departmentListResultBean.getDepartId())
                .params("companyId", departmentListResultBean.getCompanyId())
                .converter(new JsonConverter<HttpResult<List<EmploymentListResultBean>>>() {
                    @Override
                    public void test() {
                        super.test();
                    }
                })
                .adapt(new FlowableBody<>());
        Flowable.combineLatest(departFlow, careerFlow, employmentFlow, (listHttpResult, listHttpResult2, listHttpResult3) -> {
            departList = listHttpResult.getItems();
            careerList = listHttpResult2.getItems();
            employList = listHttpResult3.getItems();
            Flowable.fromIterable(listHttpResult2.getItems())
                    .subscribe(bean -> {
                        for (CareerListResultBean selectedBean : SelectPostMultiActivity.selectedBeans) {
                            if (selectedBean.getId() == bean.getId()) {
                                bean.setCheck(true);
                                bean.setNum(selectedBean.getNum());
                                for (EmploymentListResultBean employmentListResultBean : employList) {
                                    if (employmentListResultBean.getPostId() == bean.getId()) {
                                        employmentListResultBean.setCheck(true);
                                    }
                                }
                            }
                        }
                    });
            return 1;
        })
                .subscribe((s) -> {
                    datas.clear();
                    if (!ListUtil.isEmpty(departList)) {
                        datas.add("部门");
                        datas.addAll(departList);
                    }
                    if (!ListUtil.isEmpty(careerList)) {
                        datas.add("岗位");
                        datas.addAll(careerList);
                    }
                    updateNum = datas.size();
                    if (!ListUtil.isEmpty(employList)) {
                        datas.add("人员");
                        updateNum = datas.size();
                        datas.addAll(employList);
                    }
                    slimAdapterEx.updateData(datas);
                }, e -> {
                    ToastUtil.showShort(Config.SERVER_ERROR);
                    System.out.println(e.toString());
                }, () -> {
                });
    }

    @Override
    protected void initData() {
        Bundle arguments = getArguments();
        departmentListResultBean = arguments.getParcelable(Config.DEPARTMENT);
    }


    @Override
    public ViewDataBinding initBinding(LayoutInflater inflater) {
        return databinding = DataBindingUtil.inflate(inflater, R.layout.fragment_recycler_view, null, false);
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

}
